var validator;
var $userAddForm = $("#user-add-form");
var $rolesSelect = $userAddForm.find("select[name='rolesSelect']");
var $roles = $userAddForm.find("input[name='roles']");
var _date = (new Date()).setMonth(new Date().getMonth() + 3) / 1000;
var _dateStr = util.common.getDateStr(_date,'yyyy-MM-dd');
$userAddForm.find('input[name="validTimeStr"]').val(_dateStr);
//$('#passwordUpdateTimeStr').text(_dateStr);
$userAddForm.find('input[name="passwordUpdateTimeStr"]').val(_dateStr);

$(function () {
    validateRule();
    initRole();
    createDeptTree();
    $MB.calenders($userAddForm.find("input[name='validTimeStr']"),false,false);
    $MB.calenders($userAddForm.find("input[name='passwordUpdateTimeStr']"),false,false);

    var  _status1 = $MB.i18n('user.actived'), _status2 = $MB.i18n('user.locked');
    $("input[name='status']").change(function () {
        var checked = $(this).is(":checked");
        var $status_label = $("#status");
        if (checked) $status_label.html(_status1);
        else $status_label.html(_status2);
    });

    $("#user-add .btn-save").click(function () {
        var name = $(this).attr("name");
//        getDept();
        if (name === 'update') {
        	$userAddForm.find('input[name="password"]').rules("remove", 'required');
        }
        var validator = $userAddForm.validate();
        var flag = validator.form();
        if (flag) {
        	$("#user-add .btn-save").attr({"disabled":"disabled"});//add by jm.hong at 2018.12.26
            if (name === "save") {
                $.post(ctx + "user/add", $userAddForm.serialize(), function (r) {
                    if (r.code === 0) {
                        closeModal();
                        $MB.n_success(r.msg);
                        $MB.refreshTable("userTable");
                    } else $MB.n_danger(r.msg);
                    $("#user-add .btn-save").removeAttr("disabled");//add by jm.hong at 2018.12.26
                });
            }
            if (name === "update") {
                $.post(ctx + "user/update", $userAddForm.serialize(), function (r) {
                    if (r.code === 0) {
                        closeModal();
                        $MB.n_success(r.msg);
                        $MB.refreshTable("userTable");
                    } else $MB.n_danger(r.msg);
                    $("#user-add .btn-save").removeAttr("disabled");//add by jm.hong at 2018.12.26
                });
            }
        }
    });

    $("#user-add .btn-close").click(function () {
        closeModal();
    });

});

function closeModal() {
    $("#user-add-button").attr("name", "save");
    validator.resetForm();
    $rolesSelect.multipleSelect('setSelects', []);
    $rolesSelect.multipleSelect("refresh");
    $userAddForm.find("input[name='username']").removeAttr("readonly");
    $userAddForm.find(".user_password").show();
    $userAddForm.find("input[name='status']").prop("checked", true);
    $("#user-add-modal-title").html($MB.i18n('user.add'));
    $("#status").html($MB.i18n('user.actived'));
//    $MB.resetJsTree("deptTree");
    $MB.closeAndRestModal("user-add");
    $userAddForm.find('input[name="validTimeStr"]').val(util.common.getDateStr(_date,'yyyy-MM-dd'));
}

function validateRule() {
    var vali_user_msg1 = $MB.i18n('vali.user.msg1'),
        vali_user_msg2 = $MB.i18n('vali.user.msg2'),
        vali_user_msg3 = $MB.i18n('vali.user.msg3'),
        vali_roles_msg = $MB.i18n('vali.roles.msg'),
        vali_email_msg1 = $MB.i18n('vali.email.msg1'),
        vali_email_msg2 = $MB.i18n('vali.email.msg2'),
        vali_sex_msg = $MB.i18n('vali.sex.msg'),
        vali_det_msg = $MB.i18n('vali.det.msg');
    var icon = "<i class='zmdi zmdi-close-circle zmdi-hc-fw'></i> ";

    // 验证用户名 add by aaron.wei 2018.12.5
    $.validator.addMethod("isUserName", function(value, element) {
        var reg = /(^[0-9A-Za-z\-_\.]+$)|(^([0-9A-Za-z\-_\.]+)@([0-9a-z\-]+\.[a-z]{2,3}(\.[a-z]{2})?)$)/;
        //var reg = /^[0-9a-zA-Z_-]{1,48}|[\\.@]{0,2}$/;
        return this.optional(element) || (reg.test(value));
    }, $MB.i18n('user.name.not.valid'));

    validator = $userAddForm.validate({
        rules: {
            username: {
                required: true,
                isUserName: true,
                minlength: 6,
                maxlength: 50,
                remote: {
                    url: "user/checkUserName",
                    type: "get",
                    dataType: "json",
                    data: {
                        username: function () {
                            return $("input[name='username']").val().trim();
                        },
                        oldusername: function () {
                            return $("input[name='oldusername']").val().trim();
                        }
                    }
                }
            },
            password: {
                required: true,
                minlength: 3,
                maxlength: 16
            },
            email: {
            	required: true,
                email: true
            },
            roles: {
                required: true
            },
            mobile: {
                isCheckTel: true
            },
            ssex: {
                required: true
            },
            deptId: {
                required: true
            }
        },
        errorPlacement: function (error, element) {
            if (element.is(":checkbox") || element.is(":radio")) {
                error.appendTo(element.parent().parent());
            } else {
                error.insertAfter(element);
            }
        },
        messages: {
            username: {
                required: icon + vali_user_msg1,
                minlength: icon + vali_user_msg2,
                remote: icon + vali_user_msg3
            },
            password: {
                required: icon + $MB.i18n('user.password.not.required'),
                minlength: icon + $MB.i18n('user.password.not.valid'),
                maxlength: icon + $MB.i18n('user.password.not.valid')
            },
            mobile: icon + $MB.i18n('vali.mobile.info'),
            roles: icon + vali_roles_msg,
            email: {
            	required: icon + vali_email_msg1,
            	email:icon + vali_email_msg2,
            },
            ssex: icon + vali_sex_msg,
            deptId: icon + vali_det_msg
        }
    });
}

function initRole() {
    $.post(ctx + "role/list", {}, function (r) {
        var data = r;
        var option = "";
        for (var i = 0; i < data.length; i++) {
            option += "<option value='" + data[i].roleId + "'>" + data[i].roleName + "</option>"
        }
        $rolesSelect.html("").append(option);
        $rolesSelect.val(null);
        var valArr = [];//初始化默认选中项
        var options = {
//            selectAllText: '所有角色',
//            allSelected: '所有角色',
            placeholder: $MB.i18n('vali.roles.msg'),
            width: '100%',
            single: true,
            selectAll: false,
            multiple: false,
            allSelected: '',
            onClose: function () {
                //console.log($rolesSelect.val());
                $roles.val($rolesSelect.val());
                validator.element("input[name='roles']");
            }
        };
        $rolesSelect.val(valArr).multipleSelect(options);
    });
}

function createDeptTree() {
    $.post(ctx + "dept/list", {}, function (r) {
    	if (r.length > 0) {
    		var data = r,
            _html = '';
	        for (let i = 0; i < data.length; i++) {
                const e = data[i];
	            _html += '<label class="custom-control custom-radio" for="depts_'+ i +'"><input class="custom-control-input" id="depts_'+ i +'" type="radio" name="deptId" value="' + e.deptId + '" /><span class="custom-control-indicator"></span><span class="custom-control-description">' + e.deptName + '</span></label>';
            }
            if (data.length > 13) {
                $('#deptTree').addClass('tpv-group-border');
            }
            $('#deptTree').html(_html);
        } else {
            //$MB.n_danger(r.msg); modify by arron.wei 2018.12.20
        }
    })
}

function getDept() {
    var ref = $('#deptTree').jstree(true);
    $("[name='deptId']").val(ref.get_selected()[0]);
}